package com.gitee.slowcreator.http.enhance.scanner;

import cn.hutool.core.util.StrUtil;
import com.gitee.slowcreator.http.annotation.HttpInterface;
import com.gitee.slowcreator.http.config.ScHttpConfig;
import com.gitee.slowcreator.http.enhance.factory.HttpProxyFactory;
import org.reflections.Reflections;
import org.reflections.scanners.Scanners;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 扫描 HttpInterface 注解 方便生成对应的代理类
 *
 * @author zxw
 * @date 2023/1/7 下午9:12
 */
public class HttpInterfaceScanner {

    private static final Map<Class<?>, HttpProxyFactory<?>> httpInterfaceCache;

    public static <T> HttpProxyFactory<?> get(Class<?> type) {

        return httpInterfaceCache.get(type);
    }

    static {

        httpInterfaceCache = new ConcurrentHashMap<>();
        // 如果没设置会进行全包扫描 要在第一次获取接口前设置 或者已经扫描完了
        // 设置包扫描路径和不设置差距会非常大 目前本项目设置0.15秒完成扫描 未设置1.33秒完成扫描 正常业务项目只会更久
        String interfacePackage = ScHttpConfig.getInterfacePackage();
        Reflections reflections;
        if (StrUtil.isBlank(interfacePackage)) {
            reflections = new Reflections();

        } else {
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
                    .addUrls(ClasspathHelper.forPackage(interfacePackage))
                    .addScanners(Scanners.TypesAnnotated);

            reflections = new Reflections(configurationBuilder);
        }

        Set<Class<?>> httpInterfaceFields = reflections.getTypesAnnotatedWith(HttpInterface.class);

        for (Class<?> clazz : httpInterfaceFields) {
            httpInterfaceCache.put(clazz, new HttpProxyFactory<>(clazz));
        }
    }
}
